import { login, logout, getUserInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { fetchNotifiedProjectList } from "@/api/project";
import {  } from "@/api/project";
import { resetRouter } from "@/router";
import { fetchProjectList } from "@/api/project";
import { fetchProjectsByStatus } from "@/api/project";

const state = {
  token: getToken(),
  id: "",
  name: "",
  avatar: "",
  roles: [],
  permissions: [],
  projects: [],
  todoList: [],
  notifications: [],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ID: (state, id) => {
    state.id = id;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions;
  },
  SET_PROJECTS: (state, projects) => {
    state.projects = projects;
  },
  SET_NOTIFICATIONS: (state, notifications) => {
    state.notifications = notifications;
  },
  SET_TODOLIST: (state, todoList) => {
    state.todoList = todoList;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { employeeId, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ employeeId: employeeId.trim(), password: password })
        .then((response) => {
          const { data } = response;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo(state.token)
        .then((response) => {
          const { data } = response;

          if (!data) {
            reject("验证失败, 请重新登录.");
          }
          
          const { id, roles, permissions, projects, name, avatar } = data;

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject("获取信息: 角色必须是一个非空列表!");
          }
          commit("SET_ID", id);
          commit("SET_ROLES", roles);
          commit("SET_PERMISSIONS", permissions);
          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_PROJECTS", projects);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get notifications info
  getNotification({ commit }, roles) {
    return new Promise((resolve, reject) => {
      let needNotification = false;
      for (const role of roles) {
        if (["超级管理员", "院所领导", "科研管理员", "专家"].includes(role)) {
          needNotification = true;
          break;
        }
      }

      if (needNotification) {
        fetchNotifiedProjectList()
          .then((response) => {
            const { data } = response;

            if (!data) {
              reject("Get notification failed!");
            }

            if (data.mid && data.mid.length > 0) {
              data.mid.forEach((mid) => {
                mid.enableMid = true;
              });
            }
            if (data.final && data.final.length > 0) {
              data.final.forEach((final) => {
                final.enableFinal = true;
              });
            }

            commit("SET_NOTIFICATIONS", [...data.mid, ...data.final]);
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      } else {
        commit("SET_NOTIFICATIONS", []);
        resolve([]);
      }
    });
  },

  // get todoList info
  getTodoList({ commit }, roles) {
    return new Promise((resolve, reject) => {
      let hasTodo = false;
      for (const role of roles) {
        if (
          [
            "超级管理员",
            "院所领导",
            "科研管理员",
            "财务管理员",
            "专家",
          ].includes(role)
        ) {
          hasTodo = true;
          break;
        }
      }

      if (hasTodo) {
        const approveList = [];
        const projectCheckList = [];
        // fetch approve list
        const fetchStatusList = [
          "等待伦理审批",
          "未通过伦理审批",
          "已通过伦理审批",
          "未通过总审批",
          "已通过总审批",
          "未通过经费审批",
        ];

        fetchProjectsByStatus(fetchStatusList)
          .then((res) => {
            if (res.data && res.data.length > 0) {
              res.data.forEach((approve) => {
                approveList.push({
                  text: approve.projectName,
                  viewUrl: `/project/view/${approve.id}`,
                  done: false,
                });
              });
            }

            if (!(roles.length === 0 && roles[0] === "财务管理员")) {
              // fetch project check list
              fetchProjectList().then((response) => {
                if (response.data && response.data.length > 0) {
                  response.data.forEach((check) => {
                    projectCheckList.push({
                      text: check.projectName,
                      viewUrl: `/approve/view//${check.id}`,
                      done: false,
                    });
                  });
                }
              });
            }

            const finalList = [...approveList, ...projectCheckList];

            commit("SET_TODOLIST", finalList);
            resolve(finalList);
          })
          .catch((error) => {
            reject(error);
          });
      } else {
        commit("SET_TODOLIST", []);
        resolve([]);
      }
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit("SET_TOKEN", "");
          commit("SET_ROLES", []);
          commit("SET_PERMISSIONS", []);
          commit("SET_PROJECTS", []);
          removeToken();
          resetRouter();

          dispatch("tagsView/delAllViews", null, { root: true });

          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_PERMISSIONS", []);
      commit("SET_PROJECTS", []);
      removeToken();
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
